package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class AddressController {

    @Autowired
    private AddressService addressService;

    //查询
    @GetMapping("/address/list")
    public ResultInfo findList(){
       List<Address> addressList = addressService.findList();
        return ResultInfo.success(addressList);
    }

    //新增
    @PostMapping("/address")
    public ResultInfo save(@RequestBody Address address){
        addressService.save(address);
        return ResultInfo.success(null);
    }

    //修改默认地址
    @PutMapping("/address/default")
    public ResultInfo updateDefault(@RequestBody Map<String,Long> map){
        Long id = map.get("id");
        addressService.updateDefault(id);
        return ResultInfo.success(null);
    }

    //查询默认地址
    @GetMapping("/address/default")
    public ResultInfo findByDefault(){
        Address address = addressService.findByDefault();
        if(address == null){
            return ResultInfo.error("您还没设置默认地址");
        }else {
            return ResultInfo.success(address);
        }
    }

    //回显地址
    @GetMapping("/address/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
       Address address = addressService.findById(id);
        if(address == null){
            return ResultInfo.error("您还没设置地址");
        }else {
            return ResultInfo.success(address);
        }
    }

    //修改地址
    @PutMapping("/address")
    public ResultInfo update(@RequestBody Address address){
        addressService.update(address);
        return ResultInfo.success(null);
    }

    //删除地址
    @DeleteMapping("/address")
    public ResultInfo delete(Long ids){
        addressService.delete(ids);
        return ResultInfo.success(null);
    }
}
